package Servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javaBean.Message;
import javaBean.User;
import useBean.UserDB;
/**
 * Servlet implementation class Login
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	String message="";
       


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String url ="/index.jsp";
		String action = request.getParameter("action");
		request.setCharacterEncoding("utf-8");

		
		//检测页面是否提交
		if(action == null)
			url="/index.jsp";
		else if(action.equals("login")) {
			try {
				url = login(request,response);
				System.out.println("登录后" + url);
			} catch (SQLException throwables) {
				throwables.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		request.setAttribute("message_d", message);
		getServletContext().getRequestDispatcher(url).forward(request, response);
	}


	private String login(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("password" + new String(request.getParameter("password").getBytes("iso-8859-1"), "utf-8"));
		String username = new String(request.getParameter("user_name").getBytes("iso-8859-1"), "utf-8");
		String password = new String(request.getParameter("password").getBytes("iso-8859-1"), "utf-8");
		String userid="";
		HttpSession session = request.getSession();

		User user = UserDB.selectUser(username);

		String url;
		if(user != null) {

			if(user.getpassword().equals(password)) {
				Cookie u = new Cookie("user_name",username);
				u.setMaxAge(60*60*24*365*2);
				u.setPath("/");
				response.addCookie(u);
				
				userid = user.getid();
				session.setAttribute("userid", userid);
				session.setAttribute("user_name", username);
				List<Message> mL = UserDB.selectU();
				request.setAttribute("MessageList", mL);
				url="/MessageList.jsp";
			}
			else {
				message = "密码错误";
				url="/index.jsp";
			}
		}
		else {
			message = "该用户不存在";
			url = "/index.jsp";
		}
		return url;		
	}	
}
